package org.ichow.scenegame.model
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import flash.utils.setTimeout;
	import org.ichow.debug.Log;
	import org.ichow.scenegame.events.SceneEvent;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	/**
	 * ...
	 * 动画加载代理
	 * 负责动画场景的加载
	 * @author M.ichow
	 */
	public class MovieProxy extends Proxy
	{
		public static const NAME:String = "MovieProxy";
		private var _lod:URLLoader;
		private var _req:URLRequest;
		private var _movies:Dictionary;
		private var _type:String;
		private var _attributes:Object;
		
		public function MovieProxy( data:Object = null )
		{
			super( NAME , data );
			_movies = new Dictionary();
		}
		
		/**
		 * 加载为二进制
		 * @param	url
		 * @param	type
		 */
		public function load( url:String , type:String = "" , attributes:Object = null ):void
		{
			_type = type;
			_attributes = attributes;
			sendNotification( SceneEvent.MOVIE_LOADING );
			if ( _movies[ _type ] == null )
			{
				_req = new URLRequest( url );
				_lod = new URLLoader();
				_lod.dataFormat = URLLoaderDataFormat.BINARY;
				_lod.addEventListener( Event.COMPLETE , onComplete );
				_lod.load( _req );
				Log.trace( "load: " + url + " type: " + _type );
			}
			else
				send();
		}
		
		/**
		 * 加载完成
		 * @param	e
		 */
		private function onComplete( e:Event = null ):void
		{
			_movies[ _type ] = e.target.data as ByteArray;
			send();
		}
		
		/**
		 * 加载完成发出通知
		 */
		private function send():void
		{
			var byte:ByteArray = _movies[ _type ] as ByteArray;
			var lod:Loader = new Loader();
			lod.contentLoaderInfo.addEventListener( Event.COMPLETE , onSendComplete );
			lod.loadBytes( byte );
		}
		
		/**
		 * 加载成功发送
		 * @param	e
		 */
		private function onSendComplete( e:Event ):void
		{
			var li:LoaderInfo = e.target as LoaderInfo;
			li.loader.removeEventListener( Event.COMPLETE , onSendComplete );
			if ( _attributes )
			{
				for ( var i:Object in _attributes )
				{
					if ( i == "width" || i == "height" )
						li.content[ i ] = li.content[ i ] * _attributes[ i ] / li[ i ];
					else
						li.content[ i ] = _attributes[ i ];
				}
			}
			sendNotification( SceneEvent.MOVIE_LOADED , li.content );
			Log.trace( "加载完成: " + _type + " > " + li.content );
		}
	}

}